<template>
  <view class="order-detail">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
		<view class="back-btn" @click="backPage()">
			<view class="back-icon"></view>
		</view>
		<view class="title">订单详情</view>
		
    </view>
    
    <!-- 订单内容区域 -->
    <view class="order-content">
      <!-- 核销码信息 -->
      <view class="verification-code">
        <view class="code">核销码 {{orderInfo.verificationCode}}</view>
        <!-- <view class="car-info">车辆:{{orderInfo.carInfo}}</view> -->
      </view>
      
      <!-- 服务内容 -->
      <view class="service-content">
        <view class="section-title">服务内容</view>
        <view class="service-item" >
          <text>{{orderInfo.serviceType.name}}</text>
          <text>¥{{orderInfo.price}}</text>
        </view>
      </view>
      
      <!-- 订单信息 -->
      <view class="order-info">
        <view class="section-title">订单信息</view>
        <view class="info-item">
          <text>原价</text>
          <text>¥{{orderInfo.reserved2}}</text>
        </view>
        <!-- 优惠显示部分 -->
        <view class="info-item">
          <text>优惠</text>
          <text v-if="coupon.type == 0">
            {{coupon.discount}}折
          </text>
          <text v-else-if="coupon.type == 1">
            ¥{{coupon.preferentialMoney}}
          </text>
          <text v-else>
            ¥0
          </text>
        </view>
		<view class="info-item">
		  <text>应付金额</text>
		  <text v-if="coupon.type == 0">
			  ¥{{orderInfo.reserved2 * (coupon.discount * 0.1)}}
		  </text>
		  <text v-else-if="coupon.type == 1">
			   ¥{{orderInfo.reserved2 - coupon.preferentialMoney}}
		  </text>
		  <text v-else>
			  {{orderInfo.reserved2}}
		  </text>
		</view>
        <view class="info-item">
          <text>实付金额</text>
          <text>¥{{orderInfo.price}}</text>
        </view>
        <view class="info-item">
          <text>订单编号</text>
          <text>{{orderInfo.id}}</text>
        </view>
        <view class="info-item">
          <text>预约时间</text>
          <text>{{orderInfo.reservationTime}}</text>
        </view>
        <view class="info-item">
          <text>支付时间</text>
          <text>{{orderInfo.payTime}}</text>
        </view>
        <view class="info-item">
          <text>核销时间</text>
          <text>{{orderInfo.verificationTime}}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-button"
          :class="{'disabled': orderInfo.status === 2}" 
          @tap="handleVerification">
      {{orderInfo.status === 2 ? '已核销' : '确认核销'}}
    </view>
  </view>
</template>

<script setup>
import request from '@/pages/util/request.js';
import baseUrl from '@/pages/util/urlConfig.js';
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'

const orderInfo = ref({});
const coupon = ref('')
// 添加请求Promise函数
function requestPromise(config) {
  return new Promise((resolve, reject) => {
    request({
      url: config.url,
      method: config.method,
      data: config.data,
      success: resolve,
      fail: reject
    });
  });
}

// 获取优惠券信息
async function getCouponInfo(couponId) {
  try {
	  // console.log("2222",couponId)
    const res = await requestPromise({
      url: baseUrl + '/wwc/coupon/' + couponId,
      method: 'GET'
    });
	// console.log("11111",res.data)
    coupon.value = res.data.data
	// console.log("coupon",coupon.value)
  } catch (e) {
    console.error('获取优惠券信息失败:', e);
    return null;
  }
}

onLoad(async (options) => {
  const instance = getCurrentInstance()
  if (instance && instance.proxy && instance.proxy.getOpenerEventChannel) {
    const eventChannel = instance.proxy.getOpenerEventChannel()
    eventChannel.on('acceptOrderDetail', async (data) => {
      orderInfo.value = data;
      
      // 如果有优惠券ID，则查询优惠券信息
      if (data.couponId) {
		  console.log(data.couponId)
        const couponInfo = await getCouponInfo(data.couponId);
        if (couponInfo) {
          // 更新订单信息中的优惠金额
          orderInfo.value.discount = couponInfo.discount || 0;
          // 如果需要显示优惠券名称，可以添加
          orderInfo.value.couponName = couponInfo.name;
        }
      }
    })
  } else {
    orderInfo.value = {}
  }
})
onMounted()
const backPage = () => {
  uni.navigateBack();
};

const handleVerification = () => {
  if (orderInfo.value.status === 2) {
      return;
    }
  
  uni.showModal({
    title: '核销此订单',
    content: '请您仔细核对订单，此操作不可撤销\n请谨慎操作！',
    cancelText: '取消',
    confirmText: '确认',
    success: async(res) => {
      if (res.confirm) {
        try {
		  const orderData = {
			status: 2,
			id: orderInfo.value.id
		  };
		  
		  // 调用后端核销接口
		  const result = await requestPromise({
			url: baseUrl + '/wwc/orders',
			method: 'PUT',
			data: orderData
		  });
		  
		  if (result.data.code === 200) {
			// 更新本地状态
			orderInfo.value.status = 2;
			orderInfo.value.verificationTime = new Date().toLocaleString();
			
			// 显示成功提示
			uni.showToast({
			  title: '核销成功',
			  icon: 'success'
			});
		  } else {
			// 显示错误信息
			uni.showToast({
			  title: result.data.msg || '核销失败',
			  icon: 'none'
			});
		  }
		} catch (error) {
		  console.error('核销失败:', error);
		  uni.showToast({
			title: '核销失败，请重试',
			icon: 'none'
		  });
		}
      }
    }
  });
};
</script>

<style lang="scss">
.order-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .nav-bar {
    background-color: #007AFF;
    color: #fff;
    padding: 44px 16px 10px;
    display: flex;
    align-items: center;
    
    .back-icon {
      width: 24px;
    }
    
    .title {
      flex: 1;
      text-align: center;
      font-size: 18px;
    }
    
    .right-icons {
      width: 24px;
    }
  }
  
  .order-content {
    padding: 16px;
    
    .verification-code {
      background-color: #fff;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 16px;
      
      .code {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 8px;
      }
      
      .car-info {
        color: #666;
      }
    }
    
    .section-title {
      font-size: 16px;
      margin-bottom: 12px;
    }
    
    .service-content, .order-info {
      background-color: #fff;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 16px;
    }
    
    .service-item, .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      color: #333;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .bottom-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 50px;
    background-color: #007AFF;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    
    &.disabled {
      background-color: #999;
    }
  }
}

.back-btn{ margin-left: 20rpx; width: 50rpx; height: 50rpx; position: relative;}	
.back-icon { width: 30px; height: 30px;}	
.back-icon::before { content: ""; position: absolute; width: 20px; height: 2px; background-color: #fff; top: 10rpx; left: 47rpx; transform: translate(-50%, -50%); }
.back-icon::after { content: ""; position: absolute; width: 10px; height: 10px; border-left: 2px solid #fff; border-bottom: 2px solid #fff; transform: rotate(45deg); top: 0rpx; left: 30rpx;}
</style>
